$(function () {
    validateData();
    allChickBox($('.i-checks'),selectCall);//查询所有单选按钮，回调方法selectCall
    initLayerDate("#start",true);
    initLayerDate("#end",true);
    $('body').on('click', '#submitActivity', function () {
        saveUpdateActivity();
    });
    $('body').on('click', '#selectCourse', function () {
        selectCourse({
            selectType:"checkbox",
            type:1,
            callback:'selectCourseCallback'
        });
    })
    selectCoupon();
    $('body').on('click', '#onBack', function () {
        onBackHistory();
    });
    //初始化图片上传
    $("body").on('click',"#activityImageBtn",function () {//封面上传
        //初始化图片上传窗口
        initUpdateFileWin({
            fileType:'img',//文类类型["img","ico","xls","pdf","zip"]
            callback:'uploadActivityCallback',
            cut:true,//开启剪切
            imgSize:DEFAULT_COURSE_IMG_SIZE,//剪切上传后生成图片的规格（开启剪切才起使用）
            aspectRatio:16/9//剪切区域的高宽比例（开启剪切才起使用）
        });
    })
    //删除图片
    $("body").on("click","#remove-image",function () {
        $("#imageJson").val("");
        $("#file-names").text("头像文件名");
        $("#create-time").text("添加时间：");
        $("#activity-image").attr("src", staticPath+"/admin/v3/img/default/default-pic.jpg");
    });
    //删除课程
    $('body').on('click','.deleteCourse',function () {
        var dataId =  $(this).parents('tr').data('id');
        var  obj = $(this).parents('tr');
        deleteSelectCourse(dataId,obj)
    });
    $('body').on('click','#deleteAllCourse',function () {
        $('#courseIds').val('');
        $('#course-content').html('');
    });
    $('body').on('click','#deleteAllCoupon',function () {
        $('#couponIds').val('');
        $('#coupon-content').html('');
    });
})//初始化完成

/**
 * 取消
 */
function onBackHistory() {
    window.history.go(-1);
}
function deleteSelectCourse(dataId,obj) {
    var courseIds=',';
    var courses = $("#courseIds").val();
    var courseId = courses.split(',');
    for(var i=0;i<courseId.length;i++){
        if(courseId[i]!=null&&courseId[i]!=''&&courseId[i]!=dataId){
            courseIds +=courseId[i]+",";
        }
    }
    if(courseIds.length>1){
        $("#courseIds").val(courseIds);
    }else{
        $("#courseIds").val("");
    }
    obj.remove();
}
//图片上传回调

/**
 * 图片上传回调
 * @param result
 */
function uploadActivityCallback(imageMap) {
    if (imageMap!=null){
        $("#imageJson").val(encodeURIComponent(JSON.stringify(imageMap)));
        var url = imageMap.pcUrlMap.large;
        $("#activity-image").attr("src",url);
        var fileName = imageMap.fileName;
        var createTime = imageMap.createTime;
        $("#file-names").text(fileName);
        $("#create-time").text("添加时间："+createTime);
    }
}

/**
 * 新增修改促销活动
 * @param status
 */
function saveUpdateActivity() {
    var  activityType1 =  $("#activityType1").val();
    var activityType = $('input[name="activityType_1"]:checked').map(function () {
        if (this.value > 0) {
            return this.value;
        }
    }).get().join(',');
    $("#activityType").val(activityType);
    var activityGiftType = $('input[name="giftType_1"]:checked').map(function () {
        if (this.value > 0) {
            return this.value;
        }
    }).get().join(',');
    $("#giftType").val(activityGiftType);
    if(activityType1==1){
        var activityAskAmount=$('input[name="askAmount"]').val();
        if(!isDecimalAndInteger(activityAskAmount)||activityAskAmount==0){
            return icModale(0,"请输入金额数，可精确到小数点后两位，如100.1");
        }
        var activitySubAmount=$('input[name="subAmount"]').val();
        if(!isDecimalAndInteger(activitySubAmount)||activitySubAmount==0){
            return  icModale(0,"请输入金额数，可精确到小数点后两位，如100.1");
        }
    }else{
        var activityAskAmount=$('input[name="askAmount"]').val();
        if(!isDecimalAndInteger(activityAskAmount)||activityAskAmount==0){
            return icModale(0,"请输入金额数，可精确到小数点后两位，如100.1~~~~~");
        }
    }
    var  activityGiftType2= $("#activityGiftType2").val();
    var  activityGiftType3= $("#activityGiftType3").val();
    if(activityGiftType2==2){
        var activityCouponCount=$('input[name="couponCount"]').val();
        if(!isNumber(activityCouponCount)||activityCouponCount==0){
            return  icModale(0,"请正确添加优惠券数为正整数不能为0");
        }
    }
    if(activityGiftType3==3){
        var activityIntegral=$('input[name="integral"]').val();
        if(!isNumber(activityIntegral)||activityIntegral==0){
            return  icModale(0,"请正确填写赠送积分为正整数不能为0");
        }
    }
    //获取课程限制最多选择三个
   var courseIds = $('input[name="courseIds"]').val();
    var split = courseIds.replace(/(^,)|(,$)/g,'').split(",");
    if(split.length>3){
        return  icModale(0,"最多赠送3个课程");
    }
    var params = $("#activitySaveForm").serializeJSON();
    params = JSON.stringify(params);
    $.ajax({
        url: baseloaction + "/admin/op/activity/addOrUpdateActivity",
        data: params,
        dataType: "json",
        type: "post",
        contentType:'application/json;charset=utf-8',
        success: function (result) {
            if (result.success == true) {
                icModale(0, result.message)
                window.location.href = baseloaction + "/admin/op/activity/toQueryOpActivityList";
            } else {
                icModale(0, result.message);
            }
        }
    });
}

/**
 * 添加课程回调
 */
function selectCourseCallback(result) {
    if(result!=null &&result.length>0){
        var courseIds = $('input[name="courseIds"]').val();
        if(courseIds==null||courseIds==''){
            courseIds =',';
        }
        var courseIdsCount =0;
        if(courseIds!=','){
            courseIdsCount = courseIds.replace(/(^,)|(,$)/g,'').split(",").length;
        }
        if(result.length>3||(courseIdsCount+result.length)>3){
            return  icModale(0,"最多赠送3个课程");
        }
        $.each(result,function (index,course) {
            var courseName =course.courseName;
            var courseSubject=course.subject;
            var coursePrice =course.orPrice;
            if(courseIds.indexOf(","+course.id+",")==-1){
                $("#course-content-table-hd").removeClass("hide");
                courseIds +=course.id+',';
                $('#course-content').append(' <tr data-id="'+course.id+'">'+
                    '<td class="text-center">'+course.id+'</td>'+
                    '<td>'+courseName+'</td>'+
                    '<td>'+courseSubject+'</td>'+
                    '<td><span class="c-red">'+coursePrice+'</span></td>'+
                    '<td class="text-center"><a class="c-master deleteCourse"  href="javascript:void(0);">删除</a></td>'+
                    '</tr>');
            }
        });
        $('input[name="courseIds"]').val(courseIds);
    }
    parentId = 0;
}

/**
 * 查找优惠券
 */
function selectCoupon() {
    $('body').on('click', '#selectCoupon', function () {
        var index = parent.layer.open({
            type: 2,
            shadeClose: false,
            shade: [0.3, '#000000'],
            title: '<strong>选择优惠券</strong>',
            area: winArea,
            content: baseloaction + "/admin/op/coupon/toOpCouponListPage?other=1",
            btn: ['选择', '取消'],
            yes: function (index, layero) {
                var selected = parent.layer.getChildFrame('body', index).find('input.i-checks:checked');
                selected.map(function () {
                    var couponIds = $('input[name="couponIds"]').val();
                    if(couponIds==null||couponIds==''){
                        couponIds =',';
                    }
                    var couponName ='';
                    var couponSubject='';
                    var couponPrice ='';
                    selected.map(function () {
                        var id = $(this).val();
                        if(couponIds.indexOf(","+id+",")==-1&&couponIds.indexOf(id+",")==-1){
                            couponIds +=id+",";
                            couponName= $(this).parents('tr').find('#coupon-name-' + id).html();
                            couponSubject=$(this).parents('tr').find('#coupon-subject-' + id).html();
                            couponPrice=$(this).parents('tr').find('#coupon-price-' + id).html().split('/')[0];
                            $('#coupon-content').append(' <tr data-id="'+id+'">'+
                                '<td class="text-center">'+id+'</td>'+
                                '<td class="text-center">'+couponName+'</td>'+
                                '<td class="text-center"><span class="c-red">'+couponPrice+'</span></td>'+
                                '<td class="text-center">'+couponSubject+'</td>'+
                                '<td class="text-center"><a class="c-master deleteCourse"  href="javascript:void(0);">删除</a></td>'+
                                '</tr>');
                        }
                    });
                    $('input[name="couponIds"]').val(couponIds);
                });
                parent.layer.close(index);
            }
        });
    })
}

/**
 *  满减  满赠(类型为1 2) 活动的显示与隐藏
 *  课程  优惠券 积分(类型为 1 2 3) 活动的显示与隐藏
 * @param em
 */
function selectCall(em) {
    var name = em.name;
    if(name=="activityType_1") {
        if(em.value=='1'){
            var activity_type_2 = $("#activity_type_2")[0].checked;
            var tb1 = document.getElementById('tb1');
            var tb1_1 = document.getElementById('tb1_1');
            if (em.checked == false) {
                if (activity_type_2 == true){
                    tb1.style.display = 'block';
                    tb1_1.style.display = 'block';
                } else {
                    tb1.style.display = 'block';
                    tb1_1.style.display = 'block';
                }
                $("#activityType1").val(em.value);
            } else {
                if (activity_type_2 == true){
                    tb1.style.display = 'block';
                    tb1_1.style.display = 'none';
                } else {
                    tb1.style.display = 'none';
                    tb1_1.style.display = 'none';
                }
                $("#activityType1").val("");
            }
        }
        if(em.value=='2'){
            var activity_type_1 = $("#activity_type_1")[0].checked;
            var tb1 = document.getElementById('tb1');
            if (em.checked == false) {
                if (activity_type_1 == true){
                    tb1.style.display = 'block';
                } else {
                    tb1.style.display = 'block';
                }
                $("#activityType2").val(em.value);
            } else {
                if (activity_type_1 == true){
                    tb1.style.display = 'block';
                } else {
                    tb1.style.display = 'none';
                }
                $("#activityType2").val("");
            }
            if (em.checked == false) {
                var tb2 = document.getElementById('tb2');
                if (tb2.style.display == 'block') {
                    tb2.style.display = 'none';
                } else {
                    tb2.style.display = 'block';
                }
                $("#activityType2").val(em.value);
            } else {
                var tb2 = document.getElementById('tb2');
                if (tb2.style.display == 'none') {
                    tb2.style.display = 'block';
                } else {
                    tb2.style.display = 'none';
                }
                $("#activityType2").val("");
            }
        }
    }
    if(name=="giftType_1") {
        if(em.value=='1'){
            var tb3 = $('.activityCourse');
            if (em.checked == false) {//未选中
                tb3.show();
                $("#activityGiftType1").val(em.value);
            } else {//选中
                tb3.hide();
                $("#activityGiftType1").val("");
            }
        }
        if(em.value=='2'){
            var tb4 = $('.activityCoupon');
            if (em.checked == false) {//未选中
                tb4.show();
                $("#activityGiftType2").val(em.value);
            } else {//选中
                tb4.hide();
                $("#activityGiftType2").val("");
            }
        }
        if(em.value=='3'){
            var tb5 = $('.activityIntegral');
            if (em.checked == false) {//未选中
                tb5.show();
                $("#activityGiftType3").val(em.value);
            } else {//选中
                tb5.hide();
                $("#activityGiftType3").val("");
            }
        }
    }
}

/**
 * str ---input className
 * @param str
 * @param selectCall
 */
function allChickBox(str, selectCall) {
    $(str).on("ifClicked", function (event) {
        selectCall(event.target);
    });
}